package com.chenjj.java.test.juc;


import org.junit.Test;

import javax.jws.soap.SOAPBinding;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 测试FetureTask并行查询数据库
 */
public class FutureTester {

    @Test
    public  void test1() throws ExecutionException, InterruptedException {
        List<Future<String>> futures = new ArrayList<>();

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        final Busniess busniess = new Busniess();

        long start = System.currentTimeMillis();
        for (int i=0 ;i<10; i++){
           Future<String> future =executorService.submit(new Callable<String>() {
               @Override
               public String call() throws Exception {
                   return busniess.doBusiness();
               }
           });

           futures.add(future);
        }
        String result = "";
        for (int i=0 ;i<futures.size();i++){
            result +=  futures.get(i).get() + "";
        }

        long end = System.currentTimeMillis();
        System.out.printf(String.format("耗时%sms",end-start));
    }

    /**
     * 查询数据库
     */
    class Busniess{
        int i = 0;
        public String doBusiness(){
            System.out.printf("begin : "+i);
            try {
                Thread.sleep(10*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello"+(i++);
        }
    }

}
